package com.zry.fertilizer.update

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.support.annotation.RequiresApi
import android.support.v4.app.NotificationCompat
import com.zry.fertilizer.MainActivity
import com.zry.fertilizer.R
import com.zry.fertilizer.config.MyApplication
import com.zry.fertilizer.retrofit.BaseApiRetrofit

class UpdateAppService : Service() {

    private var myApplication: MyApplication? = null
    private var mNotification: Notification? = null
    private var id = 1
    private var mNotifyManager: NotificationManager? = null
    private var mBuilder: Notification.Builder? = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        myApplication = MyApplication()

        if (Build.VERSION.SDK_INT >= 26) {
            notificationInit8()
        } else {
            notificationInit()
        }

        val updataUtils = UpdateUtils(this, myApplication)
        updataUtils.showDownloadAPK(BaseApiRetrofit.DownLoadApp, mBuilder, mNotifyManager)

        return super.onStartCommand(intent, flags, startId)
    }


    private fun notificationInit() {
        //通知栏内显示下载进度条
        val intent = Intent(this, MainActivity::class.java)//点击进度条，进入程序
        val pIntent = PendingIntent.getActivity(this, 0, intent, 0)
        mNotification = Notification()
        mNotification?.contentIntent = pIntent

        mNotifyManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        mBuilder = Notification.Builder(this)
        mBuilder!!.setContentTitle("追溯下载").setContentText("下载中，请稍等").setSmallIcon(R.mipmap.ic_launcher)


        //开始时候，初始化进度条
        mBuilder!!.setProgress(100, 0, false)
        mNotifyManager!!.notify(id, mBuilder!!.build())
    }


    @RequiresApi(Build.VERSION_CODES.O)
    private fun notificationInit8() {
        val channelID = "100"
        val channelName = "channel_name"
        val channel = NotificationChannel(channelID, channelName, NotificationManager.IMPORTANCE_HIGH)
        mNotifyManager = this.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        mNotifyManager?.createNotificationChannel(channel)

        mBuilder = Notification.Builder(this)
        mBuilder!!.setContentText("追溯下载")
        mBuilder!!.setContentTitle("下载中，请稍等")
        //创建通知时指定channelID
        mBuilder!!.setChannelId(channelID)
    }


    override fun onBind(intent: Intent): IBinder? {
        return null
    }
}
